<script setup lang="ts">
import type { WafListItem } from '@/apis/model/waf'
import type { MultipleConditionSearchSchema } from '@/components/multiple-condition-search'
import type { BuildTabColumnsData } from '@/utils/table'
import { Message } from '@arco-design/web-vue'
// import { addWafNodeBindApi, getApiWafQueryApi } from '@/apis/modules/waf'
import {
  getCdnNodeWafsApi,
  updateCdnWafNodeUnbindApi,
} from '@/apis/modules/cdn'
// import { getComputeMachineGroupDetailApi } from '@/apis/modules/group.ts'
import { skipModuleOptions, wafCustomOptions } from '@/constants/cdn-node'
import { getOptionsLabel } from '@/utils/cdn'
import { commonTableProps, defaultRowSelection } from '@/utils/table'

import RuleDetails from './RuleDetails.vue'

const props = withDefaults(defineProps<IProps>(), {
  visible: false,
  type: 1,
})
const emit = defineEmits<IEmit>()
const route = useRoute()
interface IProps {
  visible: boolean
  type: number
}
const {
  visible: drawerVisible,
  open: openDrawer,
  data: detailData,
} = usePopup<WafListItem>()

interface IEmit {
  (event: 'update:visible', value: boolean): void
  (event: 'refresh'): void
}

const params = ref({
  scope: 3,
  order: 'asc',
  sort: 'priority',
  action: 0,
  // sort: 'created_at',
})

const filterScheme = computed<MultipleConditionSearchSchema>(() => {
  return {
    placeholder: '默认按照规则 ID 搜索',
    maxWidth: 240,
    widgets: [
      {
        type: 'input',
        field: 'id',
        label: '规则 ID',
        message: '规则 ID 格式不正确',
        validate: validateRuleID,
        maxLength: 20,
      },
      {
        type: 'input',
        field: 'name_keyword',
        label: '规则名称',
      },
    ],
  }
})

const {
  data: tableData,
  loading,
  run,
  pagination,
} = useListRequest(getCdnNodeWafsApi, {
  params,
  immediate: false,
})
pagination.value.pageSize = 500
const { selectedKeys, onSelectChange } = useTable(run, tableData)

const columns = computed(() => {
  const rule: BuildTabColumnsData = {
    title: '执行策略',
    slotName: 'strategy',
  }

  const jumpModule: BuildTabColumnsData = {
    title: '跳过模块',
    dataIndex: 'jump',
    render({ record }) {
      const list = record.module_config.skip_module ?? []
      return list
        .map((item: number) => getOptionsLabel(skipModuleOptions, item))
        .join(',')
    },
  }
  const commonColumns: BuildTabColumnsData[] = [
    {
      title: '规则 ID',
      dataIndex: 'id',
      format: 'copy',
      width: 220,
    },
    {
      title: '规则名称',
      dataIndex: 'name',
      format: 'copy',
    },
    {
      title: '描述',
      dataIndex: 'condition_description',
    },

    {
      title: '状态',
      render({ record }) {
        return record.status === 1 ? '开启' : '关闭'
      },
      width: 80,
    },
    {
      title: '操作',
      slotName: 'action',
      dataIndex: 'action',
      width: 80,
    },
  ]
  if (props.type === 3) {
    commonColumns.splice(3, 0, jumpModule)
  } else {
    commonColumns.splice(2, 0, rule)
  }

  return buildColumns(commonColumns)
})

function handleOpen() {
  run()
  if (!route.params.id)
    return
  params.value.unbind_node_id = route.params.id as string
  params.value.module = props.type
}
// 弹窗关闭
function handleClose() {
  params.value.id = undefined
  params.value.name_keyword = ''
  emit('update:visible', false)
}
// 弹窗完成
async function handleOk() {
  if (!selectedKeys.value.length)
    return Message.error('请勾选规则')
  await updateCdnWafNodeUnbindApi({
    node_id: route.params.id,
    module: props.type,
    waf_ids: selectedKeys.value,
  })
  Message.success('操作成功')
  emit('update:visible', false)
  emit('refresh')
}
// 弹窗取消
const handleCancel = () => emit('update:visible', false)
</script>

<template>
  <a-drawer
    :visible="visible"
    title="部署规则"
    :width="1000"
    @cancel="handleCancel"
    @ok="handleOk"
    @open="handleOpen"
    @close="handleClose"
  >
    <div class="flex items-center">
      <a-select
        v-if="[1, 2].includes(props.type)"
        v-model="params.action"
        class="!w-[136px]"
        :options="
          props.type === 1
            ? [{ label: '全部执行策略', value: 0 }, ...wafCustomOptions]
            : props.type === 2
              ? [{ label: '全部执行策略', value: 0 }, ...wafStrategyOptions]
              : []
        "
        @change="run"
      />
      <multiple-condition-search
        v-model="params"
        :class="props.type === 1 || props.type === 2 ? 'ml-4' : ''"
        :schema="filterScheme"
        @search="run"
      />
    </div>

    <a-table
      v-model:selected-keys="selectedKeys"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      v-bind="commonTableProps"
      class="mb-8 mt-6"
      :pagination="false"
      :row-selection="defaultRowSelection"
      @selection-change="onSelectChange"
    >
      <template #strategy="{ record }">
        <div class="flex items-center gap-x-6px">
          <i-icons-prevent v-if="record.action === 1" />
          <i-icons-observe v-if="record.action === 3" />

          <i-icons-js v-if="record.action === 4" />
          <i-icons-inquiry v-if="record.action === 5" />
          <span>{{ getOptionsLabel(wafCustomOptions, record.action) }}</span>
        </div>
      </template>
      <template #action="{ record }">
        <a-link
          :hoverable="false"
          @click="openDrawer(record)"
        >
          <i-icons-eye />
        </a-link>
      </template>
    </a-table>
    <rule-details
      v-model="drawerVisible"
      :type="props.type"
      :rule-id="detailData?.id ?? ''"
    />
  </a-drawer>
</template>
